<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        let data = {
            name: 'zhangmeili',
            age: 18,
            hobby: [1, 2],
            school: {
                sname: '好谷'
            }
        };
        // 添加监听方法
        function arrayMethods() {

            const arrProto = Array.prototype

            const arrayMethods = Object.create(arrProto)

            const methods = ['push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse']

            methods.forEach(function(method) {

                const original = arrProto[method]

                Object.defineProperty(arrayMethods, method, {

                    value: function v(...args) {
                        console.log('set arrayMethods')
                        return original.apply(this, args)

                    }
                });
            });
            return arrayMethods;
        };
        // 观察者函数
        function observer(data) {
            if (typeof data === 'object') {
                if (Array.isArray(data)) {
                    data.__proto__ = arrayMethods()
                } else {
                    Object.keys(data).forEach(key => {
                        defineReactive(data, key, data[key])
                    })
                }
            }
        };

        function defineReactive(obj, key, val) {
            observer(val)
            Object.defineProperty(obj, key, {
                get() {
                    console.log('get')
                    return val
                },
                set(newVal) {
                    console.log('set')
                    if (newVal !== val) val = newVal
                }
            })
        };

        observer(data);
        data.hobby.push(23);
    </script>
</body>

</html>